const app = getApp()
Page({
  data: {
    loading: true,
    active: 0,
    cate_id: 0,
    page: 0,
    tabs: [],
    store: [],
  },
  //监听页面初次载入完成
  onLoad: function (event) {
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    this.getApiCate();
  },
  //下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      page: 0,
      loading: true,
      store: []
    });
    wx.showNavigationBarLoading();
    that.getApiStroe();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 1500);
  },
  //底部加载更多
  onReachBottom: function () {
    var that = this;
    that.setData({
      loading: true,
    });
    that.getApiStroe();
  },
  //行业分类
  getApiCate: function () {
    let that = this;
    app.api().Get('api/v1/allwin-store-cate', {lists:1}, function (result) {
      if (result.code == 200) {
        that.setData({
          tabs: result.data,
          cate_id: result.data[0].id,
        })
        that.getApiStroe();
      }
      wx.hideLoading();
    })
  },
  /**
   * 获取店铺
   */
  getApiStroe: function () {
    let that = this;
    if (that.data.loading) {
      var page = that.data.page + 1;
      var cate_id = that.data.cate_id;
      app.api().Get('api/v1/allwin-store-lists', { cate_id: cate_id, page: page }, function (result) {
        if (result.code == 200) {
          var store = that.data.store;
          for (let i in result.data) {
            store.push(result.data[i]);
          }
          that.setData({
            store: store,
            page: page,
          });
        }
        that.setData({
          loading: false
        })
      })
    }
  },
  //点击Tab切换
  onChange: function (event) {
    let that = this;
    var tabs = that.data.tabs;
    that.setData({
      active: event.detail.index,
      cate_id: tabs[event.detail.index].id,
      store: [],
      loading: true,
      page: 0,
    })
    that.getApiStroe();
  },
  //设置商家并关闭
  onClose(event) {
    let that = this;
    var id = event.currentTarget.id;
    wx.showModal({
      content: '确认选择当前联盟商家吗?',success: function (res) {
        if (res.confirm) {
          app.api().Post('api/v1/allwin-store-editunion', { 'store_id': id }, function (result) {
            app.wxAlert(result.msg);
          })
        }
      }
    })
  }
});